import { AnchorInfoTypeEntity } from '../entity/infoType';
import { AnchorInfoEntity } from '../entity/info';
import { DemoUserInfoEntity } from '../../demo/entity/info';
import { Init, App, Provide } from '@midwayjs/decorator';
import { BaseService, CoolTransaction } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, QueryRunner } from "typeorm";
import { IMidwayKoaApplication } from '@midwayjs/koa';
import { MemberUserInfoEntity } from "../../member/entity/info"
import { OrderInfoEntity } from "../../order/entity/info"

import { updateTime } from '../../../comm/utils'

/**
 * anchor模块-主播信息
 */
@Provide()
export class AnchorInfoService extends BaseService {

  @App()
  app: IMidwayKoaApplication;

  @InjectEntityModel(AnchorInfoEntity)
  anchorInfoEntity: Repository<AnchorInfoEntity>;

  @InjectEntityModel(AnchorInfoTypeEntity)
  anchorInfoTypeEntity: Repository<AnchorInfoTypeEntity>;

  @InjectEntityModel(DemoUserInfoEntity)
  demoUserInfoEntity: Repository<DemoUserInfoEntity>;

  @InjectEntityModel(MemberUserInfoEntity)
  memberUserInfoEntity: Repository<MemberUserInfoEntity>;

  @InjectEntityModel(OrderInfoEntity)
  orderInfoEntity: Repository<OrderInfoEntity>;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.anchorInfoEntity);
  }

  /**
   * 获取主播列表数据
   */
  async getAnchorList() {
    return this.anchorInfoEntity.find({
      select: ['id', 'anchor', 'cover', 'image', 'labels', 'status', 'permission', 'category'],
      where: { status: 1 },
    });
  }

  // 新增主播
  @CoolTransaction({
    connectionName: 'default',
  })
  async add(param: any, queryRunner?: QueryRunner) {
    // 调用原本的add，如果不需要可以不用这样写，完全按照自己的新增逻辑写
    let anchorItem = await this.demoUserInfoEntity.findBy({ id: Number(param.anchor) })
    let name = anchorItem[0].name
    let anchorName = anchorItem[0].nickname
    param.anchorName = anchorName
    param.name = name
    const result: any = await super.add(param);
    console.log(queryRunner, 'queryRunner', param, result)
    for (let item in param.image) {
      let images = {
        anchorId: result.id,
        anchorImage: param.image[item],
        type: param.labels,
        category: param.category
      }
      await queryRunner.manager.insert<AnchorInfoTypeEntity>(AnchorInfoTypeEntity, images);
    }
    // console.log(param, 'ee')
    // 你自己的业务逻辑
    return result;
  }

  // 修改主播
  @CoolTransaction({
    connectionName: 'default',
  })
  async update(param: any, queryRunner?: QueryRunner) {
    const getDate = () => {
      // 补零
      let addZero = (t) => {
        return t < 10 ? '0' + t : t;
      }
      let time = new Date();
      let Y = time.getFullYear(), // 年
        M = time.getMonth() + 1, // 月
        D = time.getDate(), // 日
        h = time.getHours(), // 时
        m = time.getMinutes(), // 分
        s = time.getSeconds(); // 秒
      if (M > 12) {
        // 注: new Date()的年月日的拼接，在月份为12月时，会出现 获取月份+1 后，为13月的bug，需要特殊处理。用moment第三方插件获取时间也可避免此问题。
        M = M - 12;
      }
      return `${Y}-${addZero(M)}-${addZero(D)} ${addZero(h)}:${addZero(m)}:${addZero(s)}`;
    }
    // 调用原本的add，如果不需要可以不用这样写，完全按照自己的新增逻辑写
    let anchorItem = await this.demoUserInfoEntity.findBy({ id: Number(param.anchor) })
    let name = anchorItem[0].name
    let anchorName = anchorItem[0].nickname
    param.anchorName = anchorName
    param.name = name
    const result: any = await super.update(param);
    // console.log(queryRunner, 'queryRunner', param, result)
    // this.anchorInfoTypeEntity.delete({ anchorId: param.id })
    let delSql = `delete from anchor_info_image where anchorId = ${param.id}`
    await this.nativeQuery(delSql)
    let imagesList = []
    let timer = getDate()
    for (let item in param.image) {
      imagesList.push('(' + param.id + ', "' + param.category + '","' + param.image[item] + '",' + param.labels + ',"' + timer + '","' + timer + '"' + ')')
    }
    let sql = `insert into anchor_info_image (anchorId, category,anchorImage,type,createTime,updateTime) values ${imagesList.join(',')}`
    // console.log(sql,'sql')
    await this.nativeQuery(sql)
    // 你自己的业务逻辑
    return result;
  }

  // 删除主播及相册
  @CoolTransaction({
    connectionName: 'default',
  })
  async delete(param: any, queryRunner?: QueryRunner) {
    // 调用原本的add，如果不需要可以不用这样写，完全按照自己的新增逻辑写
    const result: any = await super.delete(param);
    this.anchorInfoTypeEntity.delete({ anchorId: param.id })
    // 你自己的业务逻辑
    return result;
  }

  async updateMemberData() {
    let dateTime = new Date()
    let s = await this.memberUserInfoEntity.createQueryBuilder()
      .update()
      .set({ level: 0, expireTime: null })
      .where('expireTime <= :date', { date: dateTime })
      .execute();
    // .getMany()
  }

  async getAnchorTotal(queryData: any) {
    let data: any = await this.demoUserInfoEntity.findBy({})
    console.log(queryData.startTime, '123')
    let startTime = updateTime(new Date, 1)
    let endTime = updateTime(new Date, 2)
    if (queryData.startTime) {
      startTime = queryData.startTime + ' 00:00:00'
      endTime = queryData.endTime + ' 23:59:59'
    }
    for (let item in data) {
      // let totalData = await this.orderInfoEntity.findBy({ anchorId: String(data[item].id),status:1 })
      // let totalData = await this.orderInfoEntity.findBy({ anchorId: String(data[item].id), status: 1 })
      let totalData = await this.orderInfoEntity.createQueryBuilder()
        .where('orderTime >= :startTime', { startTime: startTime })
        .andWhere('orderTime <= :endTime', { endTime: endTime })
        .andWhere('status = :status', { status: 1 })
        .andWhere('anchorId = :anchorId', { anchorId: String(data[item].id) })
        .getMany()
      data[item].total = totalData.map(o => Number(o.totalPrice)).reduce((accumulator: any, currentValue: any) => accumulator + currentValue, 0).toFixed(2);
    }
    let res = {
      anchorList: data.map(o => o.nickname),
      mountList: data.map(o => o.total)
    }
    return res
  }

}
